package com.xjgc.eip.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xjgc.common.config.DbConn;
import com.xjgc.eip.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;

/**
 * 定时推送数据到汇集服务
 * @author Administrator
 *
 */
@Service
public class ZxjEip2CPutService {

	@Autowired
	DbConn db;

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	PreparedStatement pst = null;
	PreparedStatement updatePst = null;
	ResultSet rs = null;
	
	public void putData() {

		try {
			//获取Token
			String token = "";
			Form form = new Form();
			//生产环境
			form.param("grant_type", "client_credentials").param("scope", "oms.ord").param("client_id", "oms@XuJiJiTuan").param("client_secret", "6b1f4bf0-cadf-4d2a-9be6-02771f0e8600");
			String serverUri = "http://service.oms.xuji.iubang.com/ids/connect/token";
			//测试环境
//			form.param("grant_type", "client_credentials").param("scope", "oms.ord").param("client_id", "oms@XuJiJiTuan2").param("client_secret", "e69e16dd-47cc-4c07-a966-ea14acc426b8");
//			String serverUri = "http://service.oms.xuji.iubang.com/ids/connect/token";

			//开发测试--暂不启用
//			form.param("grant_type", "client_credentials").param("scope", "oms.ord").param("client_id", "oms@XuJiJiTuan2").param("client_secret", "a56597a7-a924-4f94-a225-b44546fa73dc");
//			String serverUri = "https://service.oms.cxist.com:8443/ids/connect/token";
			Client client = ClientBuilder.newClient();
			WebTarget target = client.target(serverUri);
			Response response = target.request(MediaType.APPLICATION_FORM_URLENCODED).buildPost(Entity.form(form)).submit(Response.class).get();
			String result = response.readEntity(String.class);
			JSONObject obj = JSONObject.parseObject(result);
			if (obj!=null && obj.containsKey("access_token")){
				token = obj.getString("access_token");
				System.out.println(token);
			}else{
				if (obj!=null && obj.containsKey("error")){
					System.out.println("获取token失败："+obj.containsKey("error"));
				}else{
					System.out.println("获取token失败!");
				}
				return;
			}
			
			//销售订单
			String selectSql = "select * from zxj_eip_2cvbeln t where t.ioflag = '1'"; // 定义sql，ioflag:1未读、0已读
			String updateSql1 = "update zxj_eip_2cvbeln set istatus='0',ioflag='0',id=? where no=? and ioflag='1'"; // POST新增方法,更新返回状态
			String updateSql2 = "update zxj_eip_2cvbeln set ioflag='0' where no=? and ioflag='1'"; // PUT修改方法,更新返回状态
			pst = db.getConnetion().prepareStatement(selectSql);
			rs = pst.executeQuery();
			while (rs.next()) {

				ZxjEip2CVbeln zxjEip2CVbeln = 
						new ZxjEip2CVbeln(rs.getString("no"), rs.getString("suppliername"), rs.getString("customerorderno"), 
						rs.getString("customername"), rs.getString("projectname"), rs.getString("tendersbatchno"), sdf.format(rs.getDate("orderdate")), 
						sdf.format(rs.getDate("demanddate")), sdf.format(rs.getDate("determinedate")), sdf.format(rs.getDate("shipmentdate")), 
						rs.getString("status"),rs.getString("shipmentstatus"), rs.getString("deliverystatus"), new String[]{rs.getString("tags")}, 
						new Remark(rs.getString("labels")), rs.getString("categoryCode"), rs.getString("materialClassCode"),rs.getString("id"));
				System.out.println("销售订单:"+ JSON.toJSONString(zxjEip2CVbeln));
				
				if(rs.getString("status").equals("1")) {//确认状态
					if(rs.getString("mstatus").equals("1")) {//新增-销售订单操作
						String flag = postZxjEipCVbeln(zxjEip2CVbeln,token);
						if (flag!=null && !flag.equals("")){
							//更新销售订单
							updatePst = db.getConnetion().prepareStatement(updateSql1);
							updatePst.setString(1, flag.substring(1, flag.length()-1));
							updatePst.setString(2, rs.getString("no"));
							updatePst.execute();
							updatePst.close();
						}
					}else if(rs.getString("mstatus").equals("2")){//修改--销售订单操作
						
						String flag = putZxjEipCVbeln(zxjEip2CVbeln,token,rs.getString("id"),"upt");
						if(flag=="true"||flag.equals("true")) {
							//更新销售订单
							updatePst = db.getConnetion().prepareStatement(updateSql2);
							updatePst.setString(1, rs.getString("no"));
							updatePst.execute();
							updatePst.close();
						}
					}
				}else if(rs.getString("status").equals("2")){//取消状态-删除订单操作
					
					String flag = putZxjEipCVbeln(zxjEip2CVbeln,token,rs.getString("id"),"del");
					if(flag=="true"||flag.equals("true")) {
						//更新销售订单
						updatePst = db.getConnetion().prepareStatement(updateSql2);
						updatePst.setString(1, rs.getString("no"));
						updatePst.execute();
						updatePst.close();
					}
				}
			}
			rs.close();
			pst.close();
							
			//生产订单			
			selectSql = "select * from zxj_eip_2caufnr t where t.ioflag = '1' and productionstatus <> 'X'"; // 定义sql，ioflag:1未读、0已读
			updateSql1 = "update zxj_eip_2caufnr set istatus='0',ioflag='0',id=?,salesorderid=(select id from zxj_eip_2cvbeln v where v.no =?) where no=? and ioflag='1'"; // 定义sql,更新返回状态     jjg
			updateSql2 = "update zxj_eip_2caufnr set ioflag='0' where no=? and ioflag='1'"; // PUT修改方法,更新返回状态
			pst = db.getConnetion().prepareStatement(selectSql);
			rs = pst.executeQuery();
			ZxjEip2CAufnr zxjEip2CAufnr = new ZxjEip2CAufnr("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", null, null, null, "","");
			
			while (rs.next()) {
				
				if (rs.getString("procedures")==null || rs.getString("procedures").equals("")){
					zxjEip2CAufnr = new ZxjEip2CAufnr(rs.getString("no"), rs.getString("salesOrderId"), rs.getString("salesOrderNo"), 
							rs.getString("customerOrderRowNo"), rs.getString("salesOrderLineProjectsNo"), rs.getString("materialNo"), rs.getString("specificationType"), 
							rs.getString("demandQuantity"), sdf.format(rs.getDate("requiredDate")), sdf.format(rs.getDate("plannedStartUpTime")), 
							sdf.format(rs.getDate("plannedEndTime")),sdf.format(rs.getDate("actualStartTime")),sdf.format(rs.getDate("actualEndTime")),rs.getString("status"), 
							rs.getString("productionStatus"), new String[]{rs.getString("tags")}, new procedures2(null,null), new Remark(rs.getString("labels")),rs.getString("id"),rs.getString("unit"));
					System.out.println("生产订单:"+ JSON.toJSONString(zxjEip2CAufnr));
				}else{
					procedures1 p1 = new procedures1("","","","","","","","");
					procedures1 p2 = new procedures1("","","","","","","","");
					procedures2 p3 = new procedures2(p1,p2);
					
					zxjEip2CAufnr = new ZxjEip2CAufnr(rs.getString("no"), rs.getString("salesOrderId"), rs.getString("salesOrderNo"), 
							rs.getString("customerOrderRowNo"), rs.getString("salesOrderLineProjectsNo"), rs.getString("materialNo"), rs.getString("specificationType"), 
							rs.getString("demandQuantity"), sdf.format(rs.getDate("requiredDate")), sdf.format(rs.getDate("plannedStartUpTime")), 
							sdf.format(rs.getDate("plannedEndTime")),sdf.format(rs.getDate("actualStartTime")),sdf.format(rs.getDate("actualEndTime")),rs.getString("status"), 
							rs.getString("productionStatus"), new String[]{rs.getString("tags")}, p3, new Remark(rs.getString("labels")),rs.getString("id"),rs.getString("unit"));
					System.out.println("生产订单:"+ JSON.toJSONString(zxjEip2CAufnr));
				}
				
				if(rs.getString("status").equals("1")) {//确认状态
					if(rs.getString("mstatus").equals("1")) {//新增-生产订单操作
						String flag = postZxjEipCAufnr(zxjEip2CAufnr,token);
						if (flag!=null && !flag.equals("")){
							updatePst = db.getConnetion().prepareStatement(updateSql1);
							updatePst.setString(1, flag.substring(1, flag.length()-1));
							updatePst.setString(2, rs.getString("salesOrderNo"));
							updatePst.setString(3, rs.getString("no"));
							updatePst.execute();
							updatePst.close();
						}
					}else if(rs.getString("mstatus").equals("2")){//修改--生产订单操作
						String flag = putZxjEipCAufnr(zxjEip2CAufnr,token,rs.getString("id"),"upt");
						if (flag=="true" || flag.equals("true")){
							System.out.println("*********生产订单修改***********    "+rs.getString("id"));
							updatePst = db.getConnetion().prepareStatement(updateSql2);
							updatePst.setString(1, rs.getString("no"));
							updatePst.execute();
							updatePst.close();
						}
					}
				}else if(rs.getString("status").equals("2")){//取消状态-删除生产操作
					String flag = putZxjEipCAufnr(zxjEip2CAufnr,token,rs.getString("id"),"del");
					if (flag=="true" || flag.equals("true")){
						System.out.println("*********生产订删除***********    "+rs.getString("id"));
						updatePst = db.getConnetion().prepareStatement(updateSql2);
						updatePst.setString(1, rs.getString("no"));
						updatePst.execute();
						updatePst.close();
					}
				}
				
			}
			rs.close();
			pst.close();
			
			//生产工序报工表
			selectSql = "select * from zxj_eip_2cgxbg t where t.ioflag = '1' "; // 定义sql，ioflag:1未读、0已读
			updateSql1 = "update zxj_eip_2cgxbg set istatus='0',ioflag='0' where zzbh=? and procedureName=? and ioflag='1'"; // 定义sql,更新返回状态
			updateSql1 = "update zxj_eip_2cgxbg set ioflag='0' where zzbh=? and procedureName=? and ioflag='1'"; //PUT修改方法,更新返回状态
			
			pst = db.getConnetion().prepareStatement(selectSql);
			rs = pst.executeQuery();
			while (rs.next()) {
				String startTime = null;
				if (rs.getDate("startTime")!=null && !rs.getDate("startTime").toString().equals("")){
					startTime = sdf1.format(rs.getDate("startTime"));
				}
				String endTime = null;
				if (rs.getTimestamp("endTime")!=null && !rs.getTimestamp("endTime").toString().equals("")){
					endTime = sdf1.format(rs.getTimestamp("endTime"));
				}
				ZxjEip2CGxbg zxjEipCGxbg = new ZxjEip2CGxbg(rs.getString("salesOrderNo"), rs.getString("zzbh"), rs.getString("productionBatchNo"), rs.getString("procedureName"), 
						rs.getString("deviceNo"), startTime, endTime, rs.getString("orderDate"), //"2019-08-13 00:00:00","2019-08-13 00:00:00"
						rs.getString("tags"), rs.getString("del_flag"), rs.getString("standbyField1"), rs.getString("standbyField2"),
						rs.getString("standbyField3"), rs.getString("standbyField4"), rs.getString("standbyField5"));
				System.out.println(JSON.toJSONString(zxjEipCGxbg));
				
				if(rs.getString("del_flag").equals("1")) {//确认状态
					if(rs.getString("mstatus").equals("1")) {//新增-生产工序报工操作
						int flag = postZxjEipCGxbg(zxjEipCGxbg,token);
						if (flag == 200){
							updatePst = db.getConnetion().prepareStatement(updateSql1);
							updatePst.setString(1, rs.getString("zzbh"));
							updatePst.setString(2, rs.getString("procedureName"));
							updatePst.execute();
							updatePst.close();
						}
					}else if(rs.getString("mstatus").equals("2")){//修改--生产订单操作
						String flag = putZxjEipCGxbg(zxjEipCGxbg,token,"upt");
						if (flag=="true" || flag.equals("true")){
							updatePst = db.getConnetion().prepareStatement(updateSql2);
							updatePst.setString(1, rs.getString("zzbh"));
							updatePst.setString(2, rs.getString("procedureName"));
							updatePst.execute();
							updatePst.close();
						}
					}
				}else if(rs.getString("del_flag").equals("2")){//取消状态-删除生产操作
					String flag = putZxjEipCGxbg(zxjEipCGxbg,token,"del");
					if (flag=="true" || flag.equals("true")){
						updatePst = db.getConnetion().prepareStatement(updateSql2);
						updatePst.setString(1, rs.getString("zzbh"));
						updatePst.setString(2, rs.getString("procedureName"));
						updatePst.execute();
						updatePst.close();
					}
				}

			}
			
			rs.close();
			pst.close();
		
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} finally {
			db.closeCn();
		}
	}
	
	
	// 调用汇集服务接口,推送新增销售订单数据
	public String postZxjEipCVbeln(ZxjEip2CVbeln zxjEipVbeln,String token) {
		
		String url = "http://service.oms.xuji.iubang.com/Oms/Ord/SalesOrder";
		RestTemplate restTemplate = new RestTemplate();
		for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
		    if (httpMessageConverter instanceof StringHttpMessageConverter) {
		        ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
		    }
		}
		
		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
		headers.add("Authorization", "Bearer "+token);
      	headers.setContentType(org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8"));
      	headers.add("Accept", MediaType.APPLICATION_JSON.toString());
     	headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
      	headers.set(HttpHeaders.ACCEPT_CHARSET,StandardCharsets.UTF_8.toString());
      	HttpEntity request = new HttpEntity(JSON.toJSONString(zxjEipVbeln), headers);
      	String result="";
      	int status = 0 ;
		try {
	      	ResponseEntity resp = restTemplate.postForEntity(url,request,String.class);
	        //ResponseEntity resp = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
	        result = resp.getBody().toString();
	        status = resp.getStatusCode().value();
	        System.out.println(status+"<-->"+result); 
		} catch (Exception e) {
			System.out.println(e);
		}
	    if (status==200){
        	return result;
        }else{
        	return null;
        }    
	}
	
	// 调用汇集服务接口,推送修改销售订单数据
	public String putZxjEipCVbeln(ZxjEip2CVbeln zxjEipVbeln,String token,String id,String opType) {
		
		String url = "http://service.oms.xuji.iubang.com/Oms/Ord/SalesOrder/{id}";
		RestTemplate restTemplate = new RestTemplate();
		for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
		    if (httpMessageConverter instanceof StringHttpMessageConverter) {
		        ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
		    }
		}
		
		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
		headers.add("Authorization", "Bearer "+token);
      	headers.setContentType(org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8"));
      	headers.add("Accept", MediaType.APPLICATION_JSON.toString());
     	headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
      	headers.set(HttpHeaders.ACCEPT_CHARSET,StandardCharsets.UTF_8.toString());
      	HttpEntity request = new HttpEntity(JSON.toJSONString(zxjEipVbeln), headers);//
//      ResponseEntity resp = restTemplate.postForEntity(url,request,String.class);
      	System.out.println("***********销售订单修改**********          "+id+"     "+opType);
      	String result="";
		try {
			if(opType.equals("upt")) {
				restTemplate.put(url, request,id);
			}else if(opType.equals("del")) {
				restTemplate.delete(url, request,id);
			}
			result = "true";
		} catch (Exception e) {
			result = "false";
			System.out.println(e);
		}       
		return result;
	}
	
	// 调用汇集服务接口,推送新增生产订单数据
	public String postZxjEipCAufnr(ZxjEip2CAufnr zxjEip2CAufnr,String token) {

		String url = "http://service.oms.xuji.iubang.com/Oms/Ord/ProductionOrder";
		RestTemplate restTemplate = new RestTemplate();
		for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
		    if (httpMessageConverter instanceof StringHttpMessageConverter) {
		        ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
		    }
		}
		System.out.println("************新增上产订单*********************");
		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
		headers.add("Authorization", "Bearer "+token);
      	headers.setContentType(org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8"));
      	headers.add("Accept", MediaType.APPLICATION_JSON.toString());
     	headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
      	headers.set(HttpHeaders.ACCEPT_CHARSET,StandardCharsets.UTF_8.toString());
      	HttpEntity request = new HttpEntity(JSON.toJSONString(zxjEip2CAufnr), headers);
      	String result="";
      	int status = 0 ;
		try {
	      	ResponseEntity resp = restTemplate.postForEntity(url,request,String.class);
	        //ResponseEntity resp = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
	        result = resp.getBody().toString();
	        status = resp.getStatusCode().value();
	        System.out.println(status+"<-->"+result); 
		} catch (Exception e) {
			System.out.println(e);
		}  
	    if (status==200){
        	return result;
        }else{
        	return null;
        }    
	}
	
	// 调用汇集服务接口,推送修改生产订单数据
	public String putZxjEipCAufnr(ZxjEip2CAufnr zxjEip2CAufnr,String token,String id,String opType) {

		String url = "http://service.oms.xuji.iubang.com/Oms/Ord/ProductionOrder/{id}";	
		RestTemplate restTemplate = new RestTemplate();
		for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
		    if (httpMessageConverter instanceof StringHttpMessageConverter) {
		        ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
		    }
		}
		System.out.println("************修改上产订单*********************   "+id);
		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
		headers.add("Authorization", "Bearer "+token);
      	headers.setContentType(org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8"));
      	headers.add("Accept", MediaType.APPLICATION_JSON.toString());
     	headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
      	headers.set(HttpHeaders.ACCEPT_CHARSET,StandardCharsets.UTF_8.toString());
      	HttpEntity request = new HttpEntity(JSON.toJSONString(zxjEip2CAufnr), headers);
      	String result="";
		try {
			if(opType.equals("upt")) {
				restTemplate.put(url, request,id);
			}else if(opType.equals("del")) {
				restTemplate.delete(url, request,id);
			}
			result = "true";
		} catch (Exception e) {
			result = "false";
			System.out.println(e);
		}   
		return result;
	}
	
	// 调用汇集服务接口,推送新增生产工序报工表数据
	public int postZxjEipCGxbg(ZxjEip2CGxbg zxjEipCGxbg,String token) {
		
		String url = "http://jsservice.oms.xuji.iubang.com/process/insertProcess";
		RestTemplate restTemplate = new RestTemplate();
		for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
		    if (httpMessageConverter instanceof StringHttpMessageConverter) {
		        ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
		    }
		}

		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
		headers.add("Authorization", "Bearer "+token);
      	headers.setContentType(org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8"));
      	headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
      	headers.set(HttpHeaders.ACCEPT_CHARSET,StandardCharsets.UTF_8.toString());
      	//headers.set(HttpHeaders.ACCEPT_ENCODING,StandardCharsets.UTF_16.toString());
      	HttpEntity request = new HttpEntity(JSON.toJSONString(zxjEipCGxbg), headers);
      	String result="";
      	int status = 0 ;
		try {
	      	ResponseEntity resp = restTemplate.postForEntity(url,request,String.class);
	      	//ResponseEntity resp = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
	      	result = resp.getBody().toString();
	        status = resp.getStatusCode().value();
	        System.out.println(status+"<-->"+result); 
		} catch (Exception e) {
			System.out.println(e);
		}	       
        return status;
	}
	
	// 调用汇集服务接口,推送修改生产工序报工表数据
	public String putZxjEipCGxbg(ZxjEip2CGxbg zxjEipCGxbg,String token,String opType) {
		
		String url = "http://jsservice.oms.xuji.iubang.com/process/insertProcess";
		RestTemplate restTemplate = new RestTemplate();
		for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
		    if (httpMessageConverter instanceof StringHttpMessageConverter) {
		        ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
		    }
		}

		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
		headers.add("Authorization", "Bearer "+token);
      	headers.setContentType(org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8"));
      	headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
      	headers.set(HttpHeaders.ACCEPT_CHARSET,StandardCharsets.UTF_8.toString());
      	//headers.set(HttpHeaders.ACCEPT_ENCODING,StandardCharsets.UTF_16.toString());
      	HttpEntity request = new HttpEntity(JSON.toJSONString(zxjEipCGxbg), headers);
      	String result="";
		try {
			if(opType.equals("upt")) {
				restTemplate.put(url, request);
			}else if(opType.equals("del")) {
				restTemplate.delete(url, request);
			}
			result = "true";
		} catch (Exception e) {
			result = "false";
			System.out.println(e);
		}  	       
        return result;
	}
	
}